package edu.ccut.saturn.studio.logic.contextaction;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.ShapesDiagram;
import edu.ccut.saturn.studio.logic.parts.ShapeEditPart;

public class PasteAction extends SelectionAction {

	private List<?> list;

	public PasteAction(IWorkbenchPart part) {
		super(part);
		setId(ActionFactory.PASTE.getId());
		setText(Messages.getString("PasteAction.paste"));  //$NON-NLS-1$
	}

	@Override
	protected boolean calculateEnabled() {
		if (Clipboard.getDefault().getContents() != null) {
			this.list = (List<?>) Clipboard.getDefault().getContents();
			for (int i = 0; i < list.size(); i++) {
				ShapeEditPart part = (ShapeEditPart) list.get(i);
				Shape shape = (Shape) part.getModel();
				ShapesDiagram diagram = (ShapesDiagram) shape.getParent();
				IEditorMultiPage editorPart = (IEditorMultiPage) diagram
						.getEditor().getEditorSite().getWorkbenchWindow()
						.getWorkbench().getActiveWorkbenchWindow()
						.getActivePage().getActiveEditor();
				diagram.setEditors(editorPart);
				if (!(editorPart.hasChild(shape.getClass()))) {
					return false;
				}
				return true;
			}
		}
		return false;
	}

	public void run() {
		List relist = reverseList();
		for (int i = 0; i < relist.size(); i++) {
			ShapeEditPart part = (ShapeEditPart) relist.get(i);
			Shape shape = (Shape) part.getModel();
			ShapesDiagram diagram = (ShapesDiagram) shape.getParent();
			IEditorMultiPage editorPart = (IEditorMultiPage) diagram
					.getEditor().getEditorSite().getWorkbenchWindow()
					.getWorkbench().getActiveWorkbenchWindow().getActivePage()
					.getActiveEditor();
			ShapesDiagram activeDiagram = editorPart.getDiagram();
			Shape newShape = shape.cloneShape(getNextShapePoint(editorPart
					.getMousePoint(), i + 1), shape);
			newShape.setNextId("");
			newShape.setId(activeDiagram.getNextValidShapeId());
			// if(activeDiagram.addShape(newShape)){
			// return;
			// }
			activeDiagram.addShape(newShape);
		}
	}

	private List reverseList() {
		List relist = new ArrayList();
		for (int i = list.size()-1; i > -1; i--) {
			relist.add(list.get(i));
		}
		return relist;
	}

	private Point getNextShapePoint(Point p, int scale) {
		return new Point(p.x + scale * 100, p.y);
	}
}
